package com.ztatic.fightmode.views.drawables;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.view.MotionEvent;

public class BitmapButton implements Drawable{

	protected Bitmap _activeImage, _clickedImage, _inactiveImage;
	protected Callback _preCallback; //executes this function before _callback
										//meant for child classes
	protected Callback _callback;
	
	protected Rect _sizePos = new Rect(0, 0, 0, 0);
	
	protected enum ButtonState
	{
		ACTIVE,
		INACTIVE,
		CLICKED
	}
	protected ButtonState _state = ButtonState.ACTIVE;
	
	public BitmapButton()
	{}
	
	public void onDraw(Canvas c) {
		if(_state == ButtonState.ACTIVE)
		{
			c.drawBitmap(_activeImage, null, _sizePos, null);
		} else if(_state == ButtonState.INACTIVE)
		{
			c.drawBitmap(_inactiveImage, null, _sizePos, null);
		} else
		{
			c.drawBitmap(_clickedImage, null, _sizePos, null);
		}
	}
	
	//check if this button was clicked
	public void handlePositionEvent(MotionEvent event)
	{
		if(_state == ButtonState.INACTIVE)
			return;
		
		int action = event.getAction();
		
		//change the state if the button is being clicked
		if(_sizePos.contains((int)event.getX(), (int)event.getY()) 
				&& action == MotionEvent.ACTION_DOWN)
		{
			//set it this button to clicked
			_state = ButtonState.CLICKED;
		}
		else if(action == MotionEvent.ACTION_UP)
		{
			if(_preCallback != null)
				_preCallback.onClick(this);
			
			if(_callback != null)
				_callback.onClick(this);
			
			//set the state back to active
			if(_state != ButtonState.INACTIVE)
				_state = ButtonState.ACTIVE;
		}
	}
	
	//setters
	public void setActiveImage(Bitmap image)
	{
		_activeImage = image;
	}
	public void setInactiveImage(Bitmap image)
	{
		_inactiveImage = image;
	}
	public void setClickedImage(Bitmap image)
	{
		_clickedImage = image;
	}
	public void setCallback(Callback callback)
	{
		_callback = callback;
	}
	public void setSize(Point size) //x = width, y = height
	{
		_sizePos.set(_sizePos.left, _sizePos.top, _sizePos.left + size.x, _sizePos.top + size.x);
		//_sizePos.bottom = _sizePos.top + size.x; //height
	}
	public void setPosition(Point position)
	{
		_sizePos.offsetTo(position.x, position.y);
	}
	public void setActive(boolean isActive)
	{
		if(isActive)
		{
			if(_state == ButtonState.INACTIVE)
				_state = ButtonState.ACTIVE;
		}
		else
		{
			_state = ButtonState.INACTIVE;
		}
	}
	
	//used to handle events produced from this button
	public static interface Callback
	{
		public void onClick(BitmapButton clickedButton);
	}
}
